<template>
  <div class="channel-edit-container">
    <!-- 我的频道标题 -->
    <van-cell title="我的频道">
      <template #default>
        <van-button
          plain
          round
          type="danger"
          size="mini"
          class="edit-btn"
          @click="isEdit=!isEdit"
        >{{ isEdit ? '编辑' : '完成' }}
        </van-button>
      </template>
    </van-cell>
    <!--@namespace data.some_unres_var-->
    <!-- 我的频道宫格 -->
    <van-grid :gutter="10" class="my-grid">
      <van-grid-item
        class="channel-item"
        v-for="(channel,index) in myChannels"
        :key="channel.id"
        :icon="(isEdit && index!==0)?'close':''"
        :text="channel.name"
        :class="{active_red:active===index}"
        @click="onChangeClick(index,channel.id)"
      />
    </van-grid>
    <!--  @click="onRemoveChannel(channel.id)"-->
    <!-- 频道推荐 -->
    <van-cell title="频道推荐"></van-cell>

    <!-- 频道推荐宫格 -->
    <van-grid :gutter="8" class="recommend-grid">
      <van-grid-item
        class="channel-item"
        v-for="value in recommeendChannels"
        :key="value.id"
        icon="plus"
        :text="value.name"
        @click="onAddChannel(value)"
      />
    </van-grid>
  </div>
</template>

<script>
// import _ from 'lodash'
import { setItem } from '../../../utils/storage.js'
import { addUserChannelAPI, deleteUserChannelAPI } from '../../../api/index.js'

export default {
  name: 'ChannelEdit',
  props: {
    myChannels: {
      type: Array,
      default: () => []
    },
    active: {
      type: Number,
      default: 0
    },
    allChannels: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      // 复杂数据类型
      myChannelsClone: this.myChannels,
      isEdit: false
    }
  },
  methods: {
    // 当添加频道时
    async onAddChannel (channel) {
      if (this.$store.state.user.token) {
        try {
          // 已登录
          await addUserChannelAPI({
            id: channel.id,
            seq: this.myChannels.length
          })
          this.$toast.success('添加成功')
        } catch (err) {
          this.$toast.fail('添加失败！')
        }
      } else {
        // 未登录
        setItem('TOUTIAO_MYCHANNELS', this.myChannels)
      }
      this.myChannelsClone.push(channel)
    },
    // 点击我的频道触发的方法
    async onChangeClick (index, channelId) {
      if (this.isEdit) {
        // 编辑状态，删除频道（当添加频道时）
        if (this.$store.state.user.token) {
          try {
            // 已登录
            await deleteUserChannelAPI(channelId)
            this.$toast.success('删除成功')
          } catch (err) {
            this.$toast.fail('删除失败！')
          }
        } else {
          // 未登录
          setItem('TOUTIAO_MYCHANNELS', this.myChannels)
        }
        // if (this.active !== index && index !== 0) {
        //   const index = this.myChannels.findIndex(channel => channel.id === id)
        //   this.myChannelsClone.splice(index, 1)
        // }
        if (this.active !== index && index !== 0) {
          this.myChannelsClone.splice(index, 1)
        }
        // 如果删除的元素索引效于等于当前高亮的索引，需要让active 减1
        if (this.active !== index && index <= this.active) {
          this.$emit('update-active', this.active - 1, true)
        }
      } else {
        // 非编辑状态 切换频道并关闭弹框
        this.$emit('update-active', index)
      }
    }
  },
  computed: {
    // 计算得出推荐频道的列表数组
    recommeendChannels () {
      // 1. 从allChannels中通过过滤器进行筛选
      const list = this.allChannels.filter(channel => {
        // 在filter中返回为true时，这个元素会添加到新数组中
        // 在filter中返回为false时，这个元素会被过滤掉
        // 当前循环的元素如果没有出现在myChannels数组里，那么返回true
        return !this.myChannels.find(myChannels => myChannels.id === channel.id)
      })
      console.log('推荐列表', list)
      return list
    }
    // loash库 内置方法
    // newrecommeendChannels () {
    //   // differenceBy(目标数组，差异数组，比较条件)
    //   return _.differenceBy(this.allChannels, this.myChannels, 'id')
    // }
  }
}
</script>

<style scoped lang="less">
.channel-edit-container {
  .my-grid {
    :deep(.active_red) {
      .van-grid-item__text {
        color: deeppink !important;
      }
    }

    .edit-btn {
      padding: 0 12px;
    }

    :deep(.channel-item) {
      .van-grid-item__content {
        background-color: #f5f5f6;
      }

      .van-grid-item__text {
        font-size: 12px;
        color: #222222;
        margin-top: 0;
      }

      .van-icon-close {
        position: absolute;
        font-size: 16px;
        top: -7px;
        right: -7px;
        color: #d9d6d9;
      }
    }
  }

  .recommend-grid {
    :deep(.channel-item) {
      .van-grid-item__content {
        white-space: nowrap;
        flex-direction: row;
        background-color: #f5f5f6;
        padding: 16px 4px;
      }

      .van-grid-item__text {
        font-size: 12px;
        color: #222222;
        margin-top: 0;
      }

      .van-icon-plus {
        font-size: 12px;
        margin-right: 2px;
      }
    }
  }
}
</style>
